package infrastructure;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class DataReader {
    private String fileName;
    private File file;
    private String separator;
    public DataReader (String fileName, String separator) throws Exception{
        this.fileName = fileName;
        this.separator = separator;
        this.checkFile();
    }

    private void checkFile() throws Exception {
        this.file = new File(this.fileName);
        if (!this.file.exists()) {
            throw new Exception ("Invalid File " + this.fileName);
        }
    }
    
    public List<String[]> getData() throws Exception{
        String[] row;
        List<String[]> data = new ArrayList();
        if(this.file.canRead()){
            FileInputStream fileInputReader = new FileInputStream(this.file);
            DataInputStream in = new DataInputStream(fileInputReader);
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null){
                row = strLine.split(this.separator);
                data.add(row);
            }
            
            br.close();
            isr.close();
            in.close();
            fileInputReader.close();
        }           
        
        return data;
    }

    public List<String> getDataByLines() throws Exception{
        
        List<String> data = new ArrayList();
        if(this.file.canRead()){
            FileInputStream fileInputReader = new FileInputStream(this.file);
            DataInputStream in = new DataInputStream(fileInputReader);
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null){
                data.add(strLine);
            }
            
            br.close();
            isr.close();
            in.close();
            fileInputReader.close();
        }           
        
        return data;
    }

    
    public File getFile(){
        return this.file;
    }
}
